<!--
 * @Author: [kangjie]
 * @Date: 2022-04-06 14:32:03
 * @LastEditors: [kangjie]
 * @LastEditTime: 2022-04-06 15:13:40
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./js/vue-2.6.12.js"></script>
  <script src="./js/vue-router-3.4.3.js"></script>
</head>

<body>
  <div id="app">
    <!-- 使用路由 -->
    <div>
      <router-link to="/a">去A路由</router-link>
      <router-link to="/b">去B路由</router-link>
    </div>
    <div>
      <router-view></router-view>
    </div>
    <button @click="$router.push('/a')">跳转去A路由</button>
    <button @click="$router.push('b')">跳转去B路由</button>
    <button @click="toPathA">跳转到A路由传递参数</button>
    <button @click="toPathB">跳转到B路由传递参数</button>
  </div>
  <script>
    let myA = {
      data() {
        return {
          id: null,
          username: ""
        }
      },
      template: `
        <div>A组件-{{id}}-{{username}}</div>
      `,
      created() {
        console.log(this.$route);
        this.id=this.$route.query.id;
        this.username=this.$route.query.username;
        
      }
    };
    let myB = {
      template: `
        <div>B组件</div>
      `,
      created(){
        console.log(this.$route,'直接打印路由对象');
      }
    };
    let routes = [
      {
        path: "/a",
        component: myA
      }, {
        path: '/b',
        component: myB,
        // 路由名称
        name:'bRoute'
      }
    ];
    let router = new VueRouter({
      routes,
      // 切换路由模式
      // mode:'history'
      mode:'hash'
    });
    new Vue({
      el: '#app',
      router,
      data: {

      },
      methods: {
        // 跳转到A页面
        toPathA() {
          // 编程式导航
          this.$router.push({
            // 直接拼接在地址栏上--有效
            // path: '/a?id=1&username="张三"',
            path: '/a',
            // 有效传参
            query:{id:1,username:'李四'},
            // 无效传参
            // params:{
            //   id:1,
            //   username:'王五'
            // }
          });
        },
        // 跳转到B页面
        toPathB() {
          // 传递参数的第二种方式
          this.$router.push({
            name:'bRoute',
            // 传递参数
            query:{id:1,username:'赵六'},
            // 携带的是一次性参数
            params:{gender:'男',weight:'56Kg'}
          })
        }
      }
    })
  </script>
</body>

</html>